<?php
/**
 * Created by PhpStorm.
 * User: lenovo
 * Date: 2017/3/27
 * Time: 10:22
 */

namespace api\modules\gps\controllers;

use common\components\gps\Haode;
use common\components\gps\Sunmu;
use common\components\tools\Api;
use common\components\tools\Tools;
use common\models\CarGpsOrder;
use common\models\CarGpsOrderStatusUpdateLog;
use common\models\GuaranteeCompany;
use wodrow\yii\rest\Controller;
use yii\base\ErrorException;
use yii\db\Exception;
use yii\httpclient\Client;

class ApiController extends Controller
{
    /**
     * 新建给车安装gps订单
     * @param int $guarantee_company_car_id 不同担保公司库的车id
     * @param string $guarantee_company_sign_code 担保公司标识
     * @param string $gps_serial_number GPS序列号
     * @param serialize(array) $data 其他信息如['plate_number'=>车牌号, 'custom_name'=>客户名, ...]
     * @desc GPS 安装
     * @return array fields 当前订单信息
     */
    public function actionAddGps($guarantee_company_car_id, $guarantee_company_sign_code, $gps_serial_number, $data = null)
    {
        $company = GuaranteeCompany::getBySignCode($guarantee_company_sign_code);
        if (!$company){
            throw new ErrorException('没有找到担保公司', 1011);
        }
        $model = new CarGpsOrder();
        $model->updated_by = \Yii::$app->user->id;
        $_data = [
            'guarantee_company_car_id' => $guarantee_company_car_id,
            'guarantee_company_id' => $company->id,
            'gps_serial_number' => $gps_serial_number,
            'status' => $model::STATUS_NOT_ADD,
            'data' => $data
        ];
        $trans = \Yii::$app->db->beginTransaction();
        try{
            $model::deleteAll(['gps_serial_number'=>$gps_serial_number]);
            $model::deleteAll(['guarantee_company_car_id' => $guarantee_company_car_id, 'guarantee_company_id' => $company->id]);
            if ($model->load(['car_gps_order'=>$_data],'car_gps_order')&&$model->validate()){
                // 平台添加
                $plat = $model::getPlatForm($model->gps_serial_number);
                $plat->order = $model;
                $r = $plat->addGps();
                if (!$model->save()){
                    throw new ErrorException(Tools::makeModelGetErrorsToStringAndGetIt($model));
                }
                // 添加日志
                $log = New CarGpsOrderStatusUpdateLog();
                $log->order_id = $model->id;
                $log->time = time();
                $log->old_status = $model->isNewRecord ? 0 : $model->status;
                $log->new_status = $model->status;
                $log->order_data = serialize($model->toArray());
                if (!$log->save()) {
                    throw new ErrorException(Tools::makeModelGetErrorsToStringAndGetIt($log));
                }
//                return $r;
            }else{
                throw new ErrorException(Tools::makeModelGetErrorsToStringAndGetIt($model));
            }
            $trans->commit();
            $response = Api::request("/gps/api/get-gps", [
                'gps_serial_number' => $gps_serial_number,
                'is_direct' => 0,
                'other_data' => $data,
            ]);
            $_r = Tools::objectToArray(json_decode($response->content));
            return [
                'model' => $model->toArray(),
                'gps_response' => $r,
                'get_gps' => $_r,
                'get_gps_response' => $_r['data'],
            ];
        }catch (Exception $e){
            $trans->rollBack();
            throw $e;
        }
    }

    /**
     * GPS 状态修改
     * @desc GPS 状态修改
     * @param string $guarantee_company_car_id 担保公司库的车id
     * @param string $guarantee_company_sign_code 担保公司标识
     * @param int $new_status 10/未安装;11/安装中;12/已安装;13/已上线;14/报警;
     * @return array fields gps订单数据
     */
    /*public function actionStatusUpdate($guarantee_company_car_id, $guarantee_company_sign_code, $new_status)
    {
        $model = CarGpsOrder::findOne([
            'guarantee_company_car_id' => $guarantee_company_car_id,
            'guarantee_company_sign_code' => $guarantee_company_sign_code,
        ]);
        if (!$model){
            throw new ErrorException("未找到数据", 1011);
        }
        if (!array_key_exists($new_status, CarGpsOrder::getStatus())){
            throw new ErrorException("未找到状态", 1012);
        }
        if ($model->status == $new_status){
            throw new ErrorException("状态没有改变", 1013);
        }else{
            $model->status = $new_status;
        }
        $tr = \Yii::$app->db->beginTransaction();
        try {
            $model->save(); // CarGpsOrder aftersave()事件
            $tr->commit();
            return $model->toArray();
        } catch (\yii\db\Exception $e) {
            $tr->rollBack();
            throw $e;
        }
    }*/

    /**
     * GPS 获取gps
     * @desc 获取gps
     * @param string $gps_serial_number gps 序列号
     * @param boolen $is_direct 不经过数据库直接获取
     * @param serialize $other_data
     * @return array fields gps订单数据
     */
    public function actionGetGps($gps_serial_number, $is_direct = 0, $other_data = '')
    {
        $x = CarGpsOrder::getGps($gps_serial_number, $is_direct, unserialize($other_data));
        return $x;
    }

    /**
     * GPS 获取定位信息
     * @desc 获取gps定位信息
     * @param string $gps_serial_number gps 序列号
     * @param boolen $is_direct 不经过数据库直接获取
     * @param serialize $other_data
     */
    public function actionGetLocationMapData($gps_serial_number, $is_direct = 1, $other_data = '')
    {
        $other_data = unserialize($other_data);
        $platform = CarGpsOrder::getPlatForm($gps_serial_number);
        if ($is_direct){
            $model = new CarGpsOrder();
            $platform->order = $model;
            $platform->order->gps_serial_number = $gps_serial_number;
            $platform->order->other_data = $other_data;
        }
        $r = $platform->getGpsLocationData();
        return $r;
    }

    /**
     * 隼目新建用户
     * @desc 隼目gps为组织新建用户
     * @param string $clientName 组织名称
     * @param string $userName 用户名（可空）
     * @param string $loginName 登录名
     * @param string $loginPwd 登陆密码
     * @return object 接口返回结果
     */
    public function actionAddUser4Sunmu($clientName, $userName=null, $loginName, $loginPwd)
    {
        $data = [
            'clientName' => $clientName,
            'userName' => $userName,
            'loginName' => $loginName,
            'loginPwd' => $loginPwd,
        ];
        $sunmu = new Sunmu();
        $r = $sunmu->addUser($data);
        return $r;
    }
}